import { expandField } from '@src/component/form/util'
/** 
* @description 将form对象转成客户对象，用于提交表单 
*/
import i18n from '@src/locales'
import { formatAddress, isEmpty } from 'pub-bbx-utils';

import { handlerMaterialList } from '@src/modules/task/view/components/materialUtil.js';

export function packToReceipt(fields, form, taskSettlement, finalTotalAmount) {
  let expenseSheet = {
    sparePartsExpense: [],
    sparePartsReturnExpense: [], // 备件返还
    serviceExpense: [],
    discountExpense: {
      taskId: form.id,
      type: '折扣',
      number: 1,
      salePrice: form.disExpense
    },
    materialExpense: [], // 物料核销
    materialReturnExpense: [], // 物料返还
    finalTotalAmount: finalTotalAmount,
  };

  let task = {
    id: form.id,
    attribute: {},
    attachment: [],
    banProductIds: form.banProductIds, // 物料返还需要禁用的产品ids
    createProByMat: form.createProByMat, // 物料核销需要新建的产品	
    taskSettlement: taskSettlement
  };

  let subForms = []
  let settlementCurrency = form?.currencyType || ''
  expandField(fields).forEach(field => {
    let { fieldName } = field;
    let value = form[fieldName];

    // 备件
    if(fieldName === 'sparepart'){
      value.forEach(part => {
        let o = {};
        o.id = part.id;
        o.taskId = form.id;
        o.name = part.name;
        o.serialNumber = part.serialNumber || '';
        o.number = Number(part.number) || 0;
        o.type = '备件';
        o.salePrice = part.oldPrice;
        o.outPrice = part.costPrice;
        o.standard = part.standard;
        o.unit = part.unit;
        o.primaryId = part.id;
        o.primaryType = part.type;
        o.modifiedPrice = part.salePrice - part.oldPrice;
        o.repertoryName = part.repertoryName;
        o.repertoryId = part.repertoryId;
        o.sparePartId = part.sparePartId;
        o.spType = part.spType;
        
        // 安装产品和安装位置
        if (part.installProductId || part.installPosition) {
          o.attribute = {
            installProductId: part.installProductId,
            installPosition: part.installPosition
          }
        }
        // 备件替换信息
        if (part.replaceProductId || part.replaceCardInfoId) {
            o.replaceProductId = part.replaceProductId
            o.replaceCardInfoId = part.replaceCardInfoId
        }
        if (part.cardInfoAttribute) {
          o.cardInfoAttribute = part.cardInfoAttribute
        }

        expenseSheet.sparePartsExpense.push(o);
      });

      return;
    }

    // 备件返还
    if(fieldName === 'sparePartsReturnExpense') {
      value.forEach(part => {
        const { 
          serialNumber, 
          name, 
          standard, 
          unit, 
          salePrice, 
          costPrice, 
          repertoryId, 
          repertoryName, 
          number, 
          description, 
          isPerson, 
          primaryId,
          primaryType,
          applySparePartMustReturnNum,
        } = part || {};

        expenseSheet.sparePartsReturnExpense.push({
          serialNumber,
          name,
          type: '备件返还',
          primaryType,
          standard,
          unit,
          salePrice,
          costPrice,
          description,
          repertoryId,
          repertoryName,
          isPerson: Boolean(isPerson),
          number,
          primaryId,
          applySparePartMustReturnNum,
        })
      });
      return;
    }

    // 服务项目
    if(fieldName === 'serviceIterm'){
      value.forEach((service,serviceIndex) => {
        let o = {};
        o.id = service.id;
        o.taskId = form.id;
        o.name = service.name;
        o.number = Number(service.number) || 0;
        o.type = '服务';
        o.salePrice = service.oldPrice;
        o.outPrice = service.costPrice;
        o.unit = service.unit;
        o.primaryId = service.id;
        o.primaryType = service.type;
        o.modifiedPrice = service.salePrice - service.oldPrice;
        o.serialNumber = service.serialNumber || '';
        o.exchangeMethod = service.exchangeMethod || ''
        o.exchangeRate = service.exchangeRate || ''
        o.salePriceCurrency = service.oldPriceCurrency || service.realPriceCurrency || 'CNY'
        o.modifiedPriceCurrency = service?.salePriceCurrency;
        o.outPriceCurrency = service.costPriceCurrency || 'CNY'
        // 产品质保状态
        o.attribute = {
          serviceQualityStatus: service?.serviceQualityStatus,
          isFree:  service?.isFree, 
          isFreeName: service?.isFreeName,
          settlementRules: service?.settlementRules, 
          settlementRulesId: service?.settlementRulesId,
          qualityStatus: service?.qualityStatus,
          // 排序标识
          currentDataOrder: serviceIndex,
          // 折扣费用
          reductionFee: Number(service?.reductionFee) || 0,
        }
        expenseSheet.serviceExpense.push(o);
      });

      return;
    }

    // 物料返还
    if(fieldName === 'materialReturn'){
      value.forEach(material => {
        let o = {}
        let attribute = {
          ...material.attribute,
          initMaterialSN:material.initMaterialSN
        }
        o.attribute = attribute,
        o.SN = material.SN,
        o.id = material.id,
        o.isReplaced = material.isReplaced,
        o.isSnManage = material.isSnManage,
        // o.materialId = material.materialId,
        // o.materialName = material.materialName,
        // o.materialSn = material.materialSn,
        o.unit = material.unit
        o.name = material.name,
        o.number = material.number,
        o.positionId = material.positionId,
        o.positionName = material.positionName,
        o.primaryId = material.primaryId || material.id,
        o.positionName = material.positionName,
        o.property = material.property,
        o.salePrice = material.salePrice || 0,
        material.SN ? o.snList = [ material.SN ] : o.snList = []
        o.snManage = material.snManage,
        o.type = material.type,
        o.taskId = form.id,
        o.warehouseId = material.warehouseId,
        o.warehouseName = material.warehouseName,
        o.warrantyStatus = material.warrantyStatus,
        o.taskId = form.id
        o.sn = material.sn ?? material.materialSn
        material.SN ? o.snList = [ material.SN ] : o.snList = []
        expenseSheet.materialReturnExpense.push(o);
      });
      task.attribute = Object.assign(task.attribute, form.materialReturnInformation)
      return;
    }

    // 物料核销
    if(fieldName === 'materialVerifyEliminate'){
      // 物料核销数据提交处理
      value.forEach(material => {
        let replacedMaterial = material.replacedMaterial ?? {}
        let attribute = material.attribute ?? {}
        let o = {
          ...material,
          attribute:{
            ...attribute,
          }
        };
        // o.attribute['replacedMaterial'] = replacedMaterial
        o.taskId = form.id
        o.name = material.materialName || material.name;
        o.number = Number(material.number) || 0;
        o.salePrice = material.salePrice || 0;
        o.unit = material.materialUnit || material.unit;
        o.sn = material.materialSn || material.sn;
        o.materialSn = material.materialSn || material.sn;
        o.property = material.materialProperty || material.property;
        o.warehouseId = material.warehouseId
        o.positionId = material.positionId || material.warehousePositionId
        o.warehouseName = material.warehouseName
        o.positionName = material.positionName || material.warehousePositionName
        material.SN ? o.snList = [ material.SN ] : o.snList = []
        material.replacedMaterialSN ? o.replacedSnList = [ material.replacedMaterialSN ] : o.replacedSnList = []
        o.type = material.type || '物料'
        o.primaryId = material.materialId || material.primaryId
        o.snManage = material.isSnManageDict || material.snManage
        o.isOutWarehouse = material.isOutWarehouse || false
        o.warrantyStatus = material.warrantyStatus
        o.exchangeMethod = material.exchangeMethod || ''
        o.exchangeRate = material.exchangeRate || ''
        o.salePriceCurrency = material.salePriceCurrency || 'CNY'
        o.isPerson = material?.isPerson ?? false

        o.attribute = {
          ...o.attribute,
          replacedMaterial,
          isFree:  material?.isFree, 
          isFreeName: material?.isFreeName,
          settlementRules: material?.settlementRules, 
          settlementRulesId: material?.settlementRulesId,
          qualityStatus: material?.qualityStatus,
        }
        
        delete o.batchNumManage
        delete o.batchNumberList
        delete o.shelfLife
        delete o.shelfLifeValue
        delete o.isPeriodManage

        expenseSheet.materialExpense.push(o);
      });
      return;
    }

    // 回执内容
    if(fieldName === 'receiptContent') {
      task.receiptContent = value || '';
      return;
    }

    // 关联表单
    if(field.formType === 'relationForm') {
      if(Array.isArray(value) && value.length > 0 ){
        value.forEach(item =>{
          let attribute = {
            parentFieldName:field.fieldName,
            ...item
          }
          subForms.push({ attribute })
        })
      }
      task.subForms = subForms
      return
    }

    if(fieldName === 'receiptAttachment'){
      // 拼附件和回执附件
      task.attachment = (value || []).map(a => {
        a.receipt = true;
        return a;
      })

      return;
    }

    // 客户签名
    if(fieldName === 'systemAutograph') {
      task.autograph = value || '';
    }

     // 里程
     if(['estimatedMileage','actualMileage','taskEstimatedMileage'].includes(fieldName)) {
      task[fieldName] = value || '';
      return
    }

    if (field.formType === 'address' && !field.isSystem) {
      let all = formatAddress(value,'');

      value = {
        ...value,
      };

      all ? value.all = all : '';

    }

    // 服务故障
    if(fieldName === 'newFaultLibrary' && isEmpty(value)) {
      value = []
    }
    task.attribute[fieldName] = value;
  });

  return {
    expenseSheet,
    task,
    settlementCurrency
  };
}

/** 
* @description 将工单对象转成form表单，用于初始化表单 
*/
export function packToForm(fields, data) {
  let { task, expenseSheet } = data;
  // 回执备件、服务项目、折扣信息
  let {
    discountExpense = {},
    sparePartsExpense = [],
    serviceExpense = [],
    materialExpense = [],
    materialReturnExpense = [],
    sparePartsReturnExpense = [],
  } = expenseSheet;
  const disExpense = discountExpense?.salePrice || 0;


  expandField(fields).forEach(field => {
    let { fieldName } = field;

    // 备件
    if(fieldName === 'sparepart') {
      sparePartsExpense.map(part => {
        part.id = part.primaryId;
        part.type = part.primaryType;
        part.costPrice = part.outPrice;

        // 计算修改后的单价
        let salePrice = isNaN(part.salePrice) ? 0 : part.salePrice;
        let modifiedPrice = isNaN(part.modifiedPrice) ? 0 : part.modifiedPrice;
        let nowPrice = salePrice + modifiedPrice;
 
        part.oldPrice = salePrice;
        part.salePrice = nowPrice.toFixed(2);
        part.modifiedPrice = modifiedPrice;

        // 直接出库的备件 设置唯一id标识
        if (part.spType == 0) part.id = `${part.sparePartId}_${part.repertoryId}`;

      });

      task.attribute[fieldName] = sparePartsExpense || [];
      return;
    }

    // 备件返还
    if(fieldName === 'sparePartsReturnExpense') {
      task.attribute[fieldName] = sparePartsReturnExpense;
      return;
    }

    // 服务项目
    if(fieldName === 'serviceIterm') {
      serviceExpense.map(service => {
        service.id = service.primaryId;
        service.type = service.primaryType;
        service.costPrice = service.outPrice;
        
        // 计算修改后的单价
        let salePrice = isNaN(service.salePrice) ? 0 : service.salePrice;
        let modifiedPrice = isNaN(service.modifiedPrice) ? 0 : service.modifiedPrice;
        let nowPrice = salePrice + modifiedPrice;

        service.oldPrice = salePrice;
        service.salePrice = nowPrice.toFixed(2);
        service.modifiedPrice = modifiedPrice;
        service.costPriceCurrency = service.outPriceCurrency || 'CNY'
        service.salePriceCurrency = service.realPriceCurrency || 'CNY'
      });

      task.attribute[fieldName] = (serviceExpense || []).map(item => {
        const { attribute, ...other } = item;
        return {
          ...attribute,
          ...other
        }
      });
      return;
    }

    // 物料核销
    if(fieldName === 'materialVerifyEliminate') {
      // 数据转换
      task.attribute[fieldName] = handlerMaterialList((materialExpense || []), (field?.setting?.materialFields || [])).map(item => {
        const { attribute, ...other } = item;
        return {
          ...attribute,
          ...other,
        }
      });
      return;
    }

    // 物料返还
    if(fieldName === 'materialReturn') {

      task.attribute[fieldName] = handlerMaterialList((materialReturnExpense || []), (field?.setting?.materialFields || []));
      return;
    }

    if(fieldName === 'receiptAttachment') {
      // 分离附件和回执附件
      if (task.attachment.length) {
        task.attribute[fieldName] = task.attachment.filter(img => img.receipt);
      }
    }
    let subForms = []

    if(field.formType === 'relationForm') {
    let value = task.subForms || [];
      if(Array.isArray(value) && value.length > 0 ){
        value.forEach(item =>{
          if(item?.attribute?.parentFieldName && field.fieldName === item.attribute.parentFieldName){
            subForms.push(item.attribute)
          }
        })
      }
      console.log(subForms, 'subFormssubForms11')
      task.attribute[fieldName] = subForms
    }
 
    
    // 里程数据回填
    if(['taskEstimatedMileage','estimatedMileage','actualMileage'].includes(fieldName)) {
      // 回执数据存于，task中。现在那 task 中的回填到 task.attribute 里
      task.attribute[fieldName] = task[fieldName]
    }
  });

  return {
    templateId: task.templateId,
    disExpense,
    ...task.attribute,
    id: task.id,
  };
}

/** 
* @description 验证物料SN数量
*/
export function materialSnValidate(form) {
  let { materialReturn = [], materialVerifyEliminate = [] } = form

  let res = false
  let message = ''

  // TODO 国际化待办
  let materialReturnValidate = materialReturn?.length > 0 && materialReturn.some(item => item.snManage === '是' && item.snList?.length !== item.number)
  if(materialReturnValidate) {
    res = true
    message = i18n.t('task.tip.materialSnTip1')
  }

  // TODO 国际化待办
  let materialVerifyEliminateValidate = materialVerifyEliminate?.length > 0 && materialVerifyEliminate.some(item => (item.isSnManageDict === '是' || item.snManage === '是') && item.snList?.length !== item.number)
  if(materialVerifyEliminateValidate) {
    res = true
    message = i18n.t('task.tip.materialSnTip2')
  }

  if(materialReturnValidate && materialVerifyEliminateValidate) {
    res = true
    message = i18n.t('task.tip.materialSnTip3')
  }

  return {
    res,
    message
  }
  
}
